var express = require("express");
var bodyParser = require("body-parser");
var multer = require("multer");
var mongoose = require("mongoose");
var template = require("art-template");
var cookieParser = require("cookie-parser")

var app = express();

app.use(express.static("www"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.engine(".html", require("express-art-template"));

// 数据库连接
mongoose.connect('mongodb://127.0.0.1/work', {
    useNewUrlParser: true
});

var db = mongoose.connection;
db.on('error', () => {
    console.log('数据库连接失败');
});
db.once('open', () => {
    console.log('数据库连接成功');
});

var User = mongoose.model('user', {
    username: String,
    psw: String,
    email: String,
    sex: Boolean,
    course: String
});

var Question = mongoose.model('question', {
    username: String,
    content: String,
    time: Date,
    ip: String,
    answers: [{
        question: String,
        content: String
    }]
});

template.defaults.imports.formatIP = function (ip) {
    var result = ip;
    result = result.substr(7, result.length - 7);
    console.log(result);
    return result;
}

template.defaults.imports.formatTime = function (t) {
    var time = new Date(t);
    var date = time.toLocaleDateString();
    var shijian = time.toLocaleTimeString();
    return date + ' ' + shijian;
}

// 首页
app.get("/", (req, res) => {
    function send(code, msg, data) {
        res.json({
            code,
            msg,
            data
        });
    };
    Question.find().select("content ip time").exec((err, data) => {
        if (err) {
            send("error", "查询失败")
        } else {

            res.render('index.html', { data });

        }
    });
})

// 注册
app.post("/regist", (req, res) => {
    function send(code, msg) {
        res.json({
            code, msg
        })
    }
    User.find({ username: req.body.username }, (err, data) => {
        if (err) {
            send("error", "系统错误，注册失败")
        } else {
            if (data.length == 0) {
                new User(req.body).save(err => {
                    if (err) {
                        send("error", "系统错误，注册失败")
                    } else {
                        send("success", "注册成功")
                    }
                })
            } else {
                send("error", "用户名已存在")
            }
        }
    })
})

// 登录
app.post("/login",(req,res)=>{
    function send(code,msg){
        res.json({
            code,msg
        })
     }
    User.find({username:req.body.username},(err,data)=>{
        if(err){
            send("error","失败")
        }else{
            if(data.length == 0){
                send("error","该用户未注册，请先注册再登录")
            }else{
               if(req.body.psw == data[0].psw){
                    res.cookie('username', req.body.username);
                   send("success","登录成功")
               }else{
                   send("error","登录失败")
               }
            }
        }

        
    })
})

// 上传头像
var storage = multer.diskStorage({
    destination:"www/uploads",
    
    filename:function(req,file,cb){
        var username = req.cookies.username;
        cb(null,username+".jpg")
    }
})
var upload = multer({storage});
app.post("/user",upload.single("photo"),(req,res)=>{
    res.json({
        code:"success",
        msg:"上传成功"
    })
})

// 问题
app.post("/question",(req,res)=>{
    req.body.ip = req.ip;
    req.body.time = new Date();
    
    function send(code,msg){
        res.json({
            code,msg
        })
     }
    //  console.log(req.body);
    Question(req.body).save((err,data)=>{
        console.log(req.body);
        if(err){
            send("error","失败")
        }else{
            send("success","成功")
        }
    })
})

app.listen(3000, () => {
    console.log("服务器已开启");
})